<template>
    <div class="wechat-login-component">
        <!-- 微信登录按钮 -->
        <div v-if="mode === 'button'" class="wechat-button-container">
            <button 
                @click="startWechatLogin"
                :disabled="isLoading"
                :class="buttonClass"
                class="wechat-login-btn"
            >
                <i v-if="!isLoading" class="fa fa-weixin"></i>
                <i v-else class="fa fa-spinner fa-spin"></i>
                <span v-if="showText" class="ml-2">{{ buttonText }}</span>
            </button>
        </div>

        <!-- 微信登录二维码模态框 -->
        <div v-if="showQrModal" class="qr-modal-overlay" @click="closeQrModal">
            <div class="qr-modal-container" @click.stop>
                <div class="qr-modal-header">
                    <h3 class="text-lg font-semibold text-gray-800">微信扫码登录</h3>
                    <button @click="closeQrModal" class="text-gray-500 hover:text-gray-700">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
                
                <div class="qr-modal-body">
                    <div v-if="qrCodeUrl" class="qr-code-container">
                        <img :src="qrCodeUrl" alt="微信登录二维码" class="qr-code-image" />
                        <p class="qr-code-tip">请使用微信扫描二维码登录</p>
                        
                        <!-- 二维码状态 -->
                        <div class="qr-status">
                            <div v-if="qrStatus === 'waiting'" class="status-waiting">
                                <i class="fa fa-clock text-blue-500"></i>
                                <span class="ml-2">等待扫码...</span>
                            </div>
                            <div v-else-if="qrStatus === 'scanned'" class="status-scanned">
                                <i class="fa fa-check text-green-500"></i>
                                <span class="ml-2">已扫码，请在手机上确认</span>
                            </div>
                            <div v-else-if="qrStatus === 'expired'" class="status-expired">
                                <i class="fa fa-exclamation-triangle text-red-500"></i>
                                <span class="ml-2">二维码已过期</span>
                                <button @click="refreshQrCode" class="ml-2 text-blue-500 hover:text-blue-700">
                                    点击刷新
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div v-else class="qr-loading">
                        <i class="fa fa-spinner fa-spin text-2xl text-gray-500"></i>
                        <p class="mt-2 text-gray-600">正在生成二维码...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 登录状态提示 -->
        <div v-if="loginStatus" class="login-status mt-2 text-center text-sm">
            <span :class="loginStatusClass">{{ loginStatus }}</span>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserInfo } from '/@/stores/userInfo'
import { ElMessage } from 'element-plus'
import { getWechatQrCode, checkWechatQrLogin, getWechatAuthUrl, loginByTempToken } from '/@/api/frontend/enneagram/wechat'

// Props
interface Props {
    mode?: 'button' | 'qr' // 登录模式：按钮模式或二维码模式
    size?: 'small' | 'medium' | 'large' // 按钮大小
    showText?: boolean // 是否显示文字
    buttonText?: string // 按钮文字
}

const props = withDefaults(defineProps<Props>(), {
    mode: 'button',
    size: 'medium',
    showText: false,
    buttonText: '微信登录'
})

// Emits
const emit = defineEmits<{
    success: [userInfo: any]
    error: [error: string]
    close: []
}>()

const router = useRouter()
const userInfo = useUserInfo()

// 响应式数据
const isLoading = ref(false)
const loginStatus = ref('')
const loginStatusClass = ref('')
const showQrModal = ref(false)
const qrCodeUrl = ref('')
const qrStatus = ref('waiting') // waiting, scanned, expired
const qrScene = ref('')
const pollTimer = ref<number | null>(null)
const isWechatBrowser = ref(false)

// 计算属性
const buttonClass = computed(() => {
    const sizeClasses = {
        small: 'w-8 h-8 text-sm',
        medium: 'w-12 h-12 text-xl',
        large: 'w-16 h-16 text-2xl'
    }
    
    return [
        'bg-green-500 text-white rounded-full flex items-center justify-center',
        'hover:bg-green-600 transition disabled:opacity-50 disabled:cursor-not-allowed',
        sizeClasses[props.size]
    ].join(' ')
})

// 检查是否在微信浏览器中
const detectWechatBrowser = (): boolean => {
    const ua = navigator.userAgent.toLowerCase()
    return ua.includes('micromessenger')
}

// 生成场景值
const generateScene = () => {
    return 'wechat_login_' + Date.now() + '_' + Math.random().toString(36).slice(2, 11)
}

// 开始微信登录
const startWechatLogin = async () => {
    if (isLoading.value) return
    
    isLoading.value = true
    loginStatus.value = '正在启动微信登录...'
    loginStatusClass.value = 'text-blue-500'
    
    try {
        // 检查是否在微信浏览器中
        if (isWechatBrowser.value) {
            // 在微信浏览器中，直接跳转到微信授权
            await redirectToWechatAuth()
        } else {
            // 在普通浏览器中，显示二维码
            await showQrCodeLogin()
        }
    } catch (error) {
        console.error('微信登录失败:', error)
        loginStatus.value = '登录失败，请重试'
        loginStatusClass.value = 'text-red-500'
        emit('error', error instanceof Error ? error.message : '登录失败')
    } finally {
        isLoading.value = false
    }
}

// 跳转到微信授权
const redirectToWechatAuth = async () => {
    try {
        const result = await getWechatAuthUrl()
        
        if (result.code === 1 && result.data.auth_url) {
            // 跳转到微信授权页面
            window.location.href = result.data.auth_url
        } else {
            throw new Error(result.msg || '获取授权URL失败')
        }
    } catch (error) {
        console.error('获取微信授权URL失败:', error)
        throw error
    }
}

// 显示二维码登录
const showQrCodeLogin = async () => {
    showQrModal.value = true
    qrStatus.value = 'waiting'
    
    try {
        await generateQrCode()
        startQrPolling()
    } catch (error) {
        console.error('生成二维码失败:', error)
        closeQrModal()
        throw error
    }
}

// 生成二维码
const generateQrCode = async () => {
    try {
        qrScene.value = generateScene()
        
        const result = await getWechatQrCode({
            scene: qrScene.value,
            expire_seconds: 600 // 10分钟过期
        })
        
        if (result.code === 1 && result.data.qr_url) {
            qrCodeUrl.value = result.data.qr_url
        } else {
            throw new Error(result.msg || '生成二维码失败')
        }
    } catch (error) {
        console.error('生成二维码失败:', error)
        throw error
    }
}

// 开始轮询二维码状态
const startQrPolling = () => {
    if (pollTimer.value) {
        clearInterval(pollTimer.value)
    }
    
    pollTimer.value = window.setInterval(async () => {
        try {
            await checkQrStatus()
        } catch (error) {
            console.error('检查二维码状态失败:', error)
        }
    }, 2000) // 每2秒检查一次
}

// 检查二维码状态
const checkQrStatus = async () => {
    try {
        const result = await checkWechatQrLogin({
            scene: qrScene.value
        })
        
        if (result.code === 1 && result.data) {
            if (result.data.success) {
                // 登录成功
                stopQrPolling()
                closeQrModal()
                
                loginStatus.value = '登录成功'
                loginStatusClass.value = 'text-green-500'
                
                // 处理登录成功
                if (result.data.user_info) {
                    userInfo.dataFill(result.data.user_info)
                    emit('success', result.data.user_info)
                    
                    // 跳转到首页或指定页面
                    setTimeout(() => {
                        router.push('/')
                    }, 1000)
                }
            } else if (result.data.status === 'scanned') {
                qrStatus.value = 'scanned'
            } else if (result.data.status === 'expired') {
                qrStatus.value = 'expired'
                stopQrPolling()
            }
        }
    } catch (error) {
        console.error('检查二维码状态失败:', error)
    }
}

// 停止轮询
const stopQrPolling = () => {
    if (pollTimer.value) {
        clearInterval(pollTimer.value)
        pollTimer.value = null
    }
}

// 刷新二维码
const refreshQrCode = async () => {
    qrCodeUrl.value = ''
    qrStatus.value = 'waiting'
    
    try {
        await generateQrCode()
        startQrPolling()
    } catch (error) {
        console.error('刷新二维码失败:', error)
        ElMessage.error('刷新二维码失败，请重试')
    }
}

// 关闭二维码模态框
const closeQrModal = () => {
    showQrModal.value = false
    qrCodeUrl.value = ''
    qrStatus.value = 'waiting'
    stopQrPolling()
    
    loginStatus.value = ''
    isLoading.value = false
}

// 检查URL中的微信登录token
const checkWechatLoginToken = () => {
    const urlParams = new URLSearchParams(window.location.search)
    const wechatToken = urlParams.get('wechat_login_token')
    
    if (wechatToken) {
        // 处理微信登录token
        handleWechatLoginToken(wechatToken)
        
        // 清除URL中的token参数
        const newUrl = window.location.pathname
        window.history.replaceState({}, document.title, newUrl)
    }
}

// 处理微信登录token
const handleWechatLoginToken = async (token: string) => {
    try {
        const result = await loginByTempToken({
            temp_token: token
        })
        
        if (result.code === 1 && result.data.user_info) {
            // 登录成功
            userInfo.dataFill(result.data.user_info)
            ElMessage.success('微信登录成功')
            emit('success', result.data.user_info)
            
            // 跳转到首页
            setTimeout(() => {
                router.push('/')
            }, 1000)
        } else {
            ElMessage.error(result.msg || '微信登录验证失败')
            emit('error', result.msg || '登录验证失败')
        }
    } catch (error) {
        console.error('验证微信登录token失败:', error)
        ElMessage.error('微信登录验证失败')
        emit('error', '登录验证失败')
    }
}

// 组件挂载时检查微信登录token
onMounted(() => {
    isWechatBrowser.value = detectWechatBrowser()
    checkWechatLoginToken()
})

// 组件卸载时清理定时器
onUnmounted(() => {
    stopQrPolling()
})
</script>

<style scoped>
.wechat-login-component {
    display: inline-block;
}

.wechat-button-container {
    display: inline-block;
}

.wechat-login-btn {
    transition: all 0.3s ease;
    border: none;
    cursor: pointer;
}

.wechat-login-btn:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(34, 197, 94, 0.4);
}

.qr-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    backdrop-filter: blur(4px);
}

.qr-modal-container {
    background: white;
    border-radius: 12px;
    padding: 24px;
    max-width: 400px;
    width: 90%;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.qr-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e5e7eb;
}

.qr-modal-body {
    text-align: center;
}

.qr-code-container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.qr-code-image {
    width: 200px;
    height: 200px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    margin-bottom: 16px;
}

.qr-code-tip {
    color: #6b7280;
    font-size: 14px;
    margin-bottom: 16px;
}

.qr-status {
    padding: 12px;
    border-radius: 8px;
    background-color: #f9fafb;
    border: 1px solid #e5e7eb;
}

.status-waiting,
.status-scanned,
.status-expired {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
}

.qr-loading {
    padding: 40px 20px;
    color: #6b7280;
}

.login-status {
    margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 640px) {
    .qr-modal-container {
        margin: 20px;
        padding: 20px;
    }
    
    .qr-code-image {
        width: 160px;
        height: 160px;
    }
}
</style>
